<template>
  <div class="order-detail-page">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="spinner"></div>
      <p>加载中...</p>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <i class="fa fa-exclamation-circle"></i>
      <p>{{ errorMessage }}</p>
      <button @click="retry" class="retry-btn">重试</button>
    </div>

    <!-- 订单详情 -->
    <div v-else-if="orderDetail" class="order-detail-container">
      <div class="page-header">
        <h2>订单详情</h2>
        <button @click="goBack" class="back-btn">返回订单列表</button>
      </div>

      <div class="order-info-card">
        <div class="card-header">
          <h3>订单信息</h3>
        </div>
        <div class="card-content">
          <div class="info-row">
            <span class="label">订单号：</span>
            <span class="value">{{ orderDetail.order_no }}</span>
          </div>
          <div class="info-row">
            <span class="label">下单时间：</span>
            <span class="value">{{ formatDate(orderDetail.create_time) }}</span>
          </div>
          <div class="info-row">
            <span class="label">订单状态：</span>
            <span class="value status-tag" :class="`status-${orderDetail.order_status}`">
              {{ getOrderStatusName(orderDetail.order_status) }}
            </span>
          </div>
          <div class="info-row">
            <span class="label">订单备注：</span>
            <span class="value">{{ orderDetail.remark || '无' }}</span>
          </div>
        </div>
      </div>

      <div class="address-card">
        <div class="card-header">
          <h3>收货信息</h3>
        </div>
        <div class="card-content">
          <div class="info-row">
            <span class="label">收货人：</span>
            <span class="value">{{ orderDetail.receiver_name }}</span>
          </div>
          <div class="info-row">
            <span class="label">联系电话：</span>
            <span class="value">{{ orderDetail.receiver_mobile }}</span>
          </div>
          <div class="info-row">
            <span class="label">收货地址：</span>
            <span class="value">{{ orderDetail.receiver_address }}</span>
          </div>
        </div>
      </div>

      <div class="goods-card">
        <div class="card-header">
          <h3>商品信息</h3>
        </div>
        <div class="card-content">
          <div v-for="item in orderDetail.items" :key="item.item_id" class="goods-item">
            <div class="goods-image">
              <img :src="item.goods_cover_img" :alt="item.goods_name" />
            </div>
            <div class="goods-info">
              <h4 class="goods-name">{{ item.goods_name }}</h4>
              <div class="goods-price-info">
                <span class="price">¥{{ formatAmount(item.goods_price) }}</span>
                <span class="quantity">x {{ item.goods_num }}</span>
              </div>
              <div class="goods-total-price">小计: ¥{{ formatAmount(item.goods_total_price) }}</div>
              <button
                v-if="orderDetail.order_status === OrderStatus.Completed"
                @click.stop="goToComment(item.goods)"
                class="comment-btn"
              >
                评价
              </button>
            </div>
          </div>
        </div>
      </div>

      <div class="summary-card">
        <div class="card-header">
          <h3>费用信息</h3>
        </div>
        <div class="card-content">
          <div class="summary-item">
            <span>商品总价：</span>
            <span>¥{{ formatAmount(orderDetail.total_amount) }}</span>
          </div>
          <div class="summary-item">
            <span>运费：</span>
            <span>¥0.00</span>
          </div>
          <div class="summary-item total">
            <span>应付总额：</span>
            <span class="total-amount">¥{{ formatAmount(orderDetail.payment_amount) }}</span>
          </div>
        </div>
      </div>

      <div class="actions-card">
        <div class="card-content">
          <div class="order-actions">
            <button
              v-if="orderDetail.order_status === OrderStatus.PendingPayment"
              class="pay-btn"
              @click="payOrder"
            >
              立即付款
            </button>
            <button
              v-if="orderDetail.order_status === OrderStatus.Delivered"
              class="confirm-btn"
              @click="confirmOrder"
            >
              确认收货
            </button>
            <button
              v-if="orderDetail.order_status === OrderStatus.PendingPayment"
              class="cancel-btn"
              @click="cancelOrder"
            >
              取消订单
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  ordersApi,
  type OrderDetail,
  OrderStatus,
  getOrderStatusName,
  formatAmount,
} from '@/api/orders'
import { ElMessage, ElMessageBox } from 'element-plus'

// 路由
const route = useRoute()
const router = useRouter()

// 响应式数据
const orderDetail = ref<OrderDetail | null>(null)
const loading = ref(false)
const error = ref(false)
const errorMessage = ref('')

// 方法
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  })
}

const getGoodsSpecs = (goods: any) => {
  // 这里应该根据实际的商品规格数据来显示
  return '规格：默认'
}

const fetchOrderDetail = async () => {
  try {
    loading.value = true
    error.value = false

    const orderId = Number(route.params.id)
    if (!orderId) {
      throw new Error('无效的订单ID')
    }

    const detail = await ordersApi.getOrderDetail(orderId)
    orderDetail.value = detail
  } catch (err) {
    console.error('获取订单详情失败:', err)
    error.value = true
    errorMessage.value = err instanceof Error ? err.message : '获取订单详情失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

const retry = () => {
  fetchOrderDetail()
}

const goBack = () => {
  router.push('/orders')
}
const goToComment = (goodsId: number) => {
  if (!orderDetail.value) return

  router.push({
    name: 'CommentPage',
    params: { goodsId },
    query: {
      orderId: orderDetail.value.order_id.toString(),
      canComment: orderDetail.value.order_status === OrderStatus.Completed ? 'true' : 'false',
    },
  })
}

const payOrder = () => {
  if (orderDetail.value) {
    router.push({
      path: '/payment',
      query: {
        order_id: orderDetail.value.order_id.toString(),
      },
    })
  }
}

const confirmOrder = async () => {
  if (!orderDetail.value) return

  try {
    await ElMessageBox.confirm('确认收货后无法撤销，确定要确认收货吗？', '确认收货', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await ordersApi.confirmOrder(orderDetail.value.order_id)
    ElMessage.success('确认收货成功')
    fetchOrderDetail()
  } catch (err) {
    if (err !== 'cancel') {
      console.error('确认收货失败:', err)
      ElMessage.error('确认收货失败')
    }
  }
}

const cancelOrder = async () => {
  if (!orderDetail.value) return

  try {
    await ElMessageBox.confirm('确定要取消这个订单吗？', '取消订单', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await ordersApi.cancelOrder(orderDetail.value.order_id)
    ElMessage.success('订单取消成功')
    fetchOrderDetail()
  } catch (err) {
    if (err !== 'cancel') {
      console.error('取消订单失败:', err)
      ElMessage.error('取消订单失败')
    }
  }
}

// 生命周期
onMounted(() => {
  fetchOrderDetail()
})
</script>

<style scoped lang="scss">
.order-detail-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;

  .loading-container,
  .error-container {
    text-align: center;
    padding: 100px 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

    i {
      font-size: 48px;
      margin-bottom: 20px;
    }

    p {
      color: #666;
      margin-bottom: 20px;
      font-size: 16px;
    }
  }

  .loading-container {
    i {
      color: #409eff;
    }
  }

  .error-container {
    i {
      color: #f56c6c;
    }
  }

  .retry-btn,
  .back-btn {
    padding: 12px 30px;
    background-color: #f5f5f5;
    color: #666;
    border: none;
    border-radius: 4px;
    font-size: 16px;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      background-color: #e6e6e6;
    }
  }

  .order-detail-container {
    .page-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      padding: 20px;
      background: white;
      border-radius: 8px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

      h2 {
        font-size: 24px;
        margin: 0;
        color: #333;
      }
    }

    .card-header {
      padding: 15px 20px;
      border-bottom: 1px solid #eee;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      border-radius: 8px 8px 0 0;

      h3 {
        margin: 0;
        font-size: 18px;
      }
    }

    .card-content {
      padding: 20px;
    }

    .info-row {
      display: flex;
      margin-bottom: 15px;

      &:last-child {
        margin-bottom: 0;
      }

      .label {
        width: 100px;
        color: #666;
        font-weight: 500;
      }

      .value {
        flex: 1;
        color: #333;

        &.status-tag {
          padding: 4px 10px;
          border-radius: 12px;
          font-size: 12px;
          font-weight: 500;

          &.status-1 {
            background-color: #f56c6c;
            color: white;
          }

          &.status-2 {
            background-color: #409eff;
            color: white;
          }

          &.status-3 {
            background-color: #67c23a;
            color: white;
          }

          &.status-4 {
            background-color: #909399;
            color: white;
          }

          &.status-5 {
            background-color: #e6a23c;
            color: white;
          }

          &.status-6 {
            background-color: #909399;
            color: white;
          }
        }
      }
    }

    .order-info-card,
    .address-card,
    .goods-card,
    .summary-card,
    .actions-card {
      background: white;
      border-radius: 8px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      margin-bottom: 20px;
      overflow: hidden;
    }

    .goods-card {
      .goods-item {
        display: flex;
        padding: 15px 0;
        border-bottom: 1px solid #eee;

        &:last-child {
          border-bottom: none;
        }

        .goods-image {
          width: 80px;
          height: 80px;
          margin-right: 20px;
          border-radius: 4px;
          overflow: hidden;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }

        .goods-info {
          flex: 1;

          .goods-name {
            font-size: 16px;
            margin-bottom: 8px;
            color: #333;
          }

          .goods-specs {
            color: #999;
            font-size: 14px;
            margin-bottom: 10px;
          }

          .goods-price-info {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .price {
              color: #f56c6c;
              font-weight: bold;
              font-size: 16px;
            }

            .quantity {
              color: #666;
            }
          }
        }
      }
    }

    .summary-card {
      .summary-item {
        display: flex;
        justify-content: space-between;
        padding: 10px 0;
        border-bottom: 1px dashed #eee;

        &:last-child {
          border-bottom: none;
        }

        &.total {
          font-weight: bold;
          font-size: 18px;
          margin-top: 10px;
          padding-top: 15px;
          border-top: 1px solid #eee;
          border-bottom: none;

          .total-amount {
            color: #f56c6c;
            font-size: 20px;
          }
        }
      }
    }

    .actions-card {
      .order-actions {
        display: flex;
        justify-content: flex-end;
        gap: 15px;

        button {
          padding: 12px 24px;
          border: none;
          border-radius: 4px;
          cursor: pointer;
          font-size: 16px;
          transition: all 0.3s;

          &.pay-btn {
            background-color: #f56c6c;
            color: white;

            &:hover {
              background-color: #e45a5a;
            }
          }

          &.confirm-btn {
            background-color: #67c23a;
            color: white;

            &:hover {
              background-color: #5daf34;
            }
          }

          &.cancel-btn {
            background-color: #909399;
            color: white;

            &:hover {
              background-color: #82848a;
            }
          }
        }
      }
    }
  }

  .spinner {
    width: 40px;
    height: 40px;
    margin: 0 auto 20px;
    border: 4px solid #f3f3f3;
    border-top: 4px solid #409eff;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }
}

@media (max-width: 768px) {
  .order-detail-page {
    padding: 10px;

    .order-detail-container {
      .page-header {
        flex-direction: column;
        gap: 15px;
        text-align: center;
      }

      .info-row {
        flex-direction: column;
        gap: 5px;

        .label {
          width: auto;
        }
      }

      .goods-card {
        .goods-item {
          .goods-image {
            width: 60px;
            height: 60px;
          }
        }
      }

      .actions-card {
        .order-actions {
          flex-direction: column;

          button {
            width: 100%;
          }
        }
      }
    }
  }
}
</style>
